<template>
  <div>
    <!--      侧边栏-->
    <el-container>
      <el-aside style="width:200px;background-color:#001529">
        <div style="height: 60px;line-height: 60px;color: rgba(255,255,255,0.62);
        display: flex;align-items: center;justify-content: center;">
          <!--      将元素设置为 Flex 容器，开启弹性布局,水平垂直居中    -->
          <span style=" font-size: 25px;">文档管理系统</span>
        </div>
        <el-menu router default-active="$route.path" background-color="#001529"
                 text-color="rgba(255,255,255,0.62)" >
          <el-menu-item index="/">
            <template slot="title">
              <!-- 菜单图标（Element UI 内置图标） -->
              <i class="el-icon-s-home"></i>
              <!-- 菜单标题文本 -->
              <span>系统首页</span>
            </template>
          </el-menu-item>
        </el-menu>
        <!--          二级菜单-->
        <el-menu background-color="#001529" text-color="rgba(255,255,255,0.62)" router default-active="$route.path">
          <!--          文档信息-->
          <el-submenu>
            <template slot="title">
              <i class="el-icon-document"></i>
              <span>文档信息</span>
            </template>
            <el-menu-item index="/Upload">文档录入</el-menu-item>
            <el-menu-item index="/Report">报表生成</el-menu-item>
          </el-submenu>
        </el-menu>
        <el-menu background-color="#001529" text-color="rgba(255,255,255,0.62)" router default-active="$route.path">
          <!--          文档管理-->
          <el-submenu >
            <template slot="title">
              <i class="el-icon-menu"></i>
              <span>文档管理</span>
            </template>
            <el-menu-item index="/Type1">文档类型一</el-menu-item>
            <el-menu-item index="/Type2">文档类型二</el-menu-item>
          </el-submenu>
        </el-menu>
        <el-menu background-color="#001529" text-color="rgba(255,255,255,0.62)" router default-active="$route.path">
          <!--          个人中心-->
          <el-submenu>
            <template slot="title">
              <i class="el-icon-user"></i>
              <span>个人中心</span>
            </template>
            <el-menu-item index="">修改密码</el-menu-item>
          </el-submenu>
        </el-menu>
      </el-aside>

      <el-container>
        <el-header>
          <!--            面包屑-->
          <el-card style="width: 1000px; height: 60px;display: flex;align-items: center;justify-content: center;margin-top: 15px">
            <div>
              <el-breadcrumb separator-class="el-icon-arrow-right" >
                <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
                <el-breadcrumb-item :to="{ path: '/document' }">文档信息</el-breadcrumb-item>
              </el-breadcrumb>
            </div>
            <!--            下拉菜单-->
            <div style="margin-left: 860px;margin-top: -25px">
              <el-dropdown placement="bottom">
                <div style="display: flex;align-items: center;">
                  <img src="@/assets/1.png" alt="" style="width: 40px;height: 40px;">
                  <span style="margin-left: 10px">用户1</span>
                </div>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item>个人信息</el-dropdown-item>
                  <el-dropdown-item @click="">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
          </el-card>
        </el-header>
                <el-main>
                  <el-card style="width: 1000px;display: flex;align-items: center;justify-content: center;">
                    <div class="input">
                      <el-form ref="uploadForm" :model="form" :rules="rules" label-width="100px" class="demo-ruleForm">
                        <el-form-item label="文档名称:" prop="name">
                          <el-input v-model="form.file_name"></el-input>
                        </el-form-item>

                        <el-form-item label="文档类型:" prop="type">
                          <el-select v-model="form.file_type" placeholder="请选择文档类型" style="width: 360px">
                            <el-option label="文档类型一" value="type1"></el-option>
                            <el-option label="文档类型二" value="type2"></el-option>
                            <el-option label="文档类型三" value="type3"></el-option>
                          </el-select>
                        </el-form-item>

                        <el-form-item label="拍照上传:">
                          <div class="camera-upload">
                            <video ref="video" autoplay width="320" height="240" v-if="isCameraActive"></video>
                            <canvas ref="canvas" style="display: none;"></canvas>
                            <el-button @click="startCamera" v-if="!isCameraActive">启动摄像头</el-button>
                            <el-button @click="capturePhoto" :disabled="!isCameraActive">拍照</el-button>
                            <el-button @click="uploadPhoto" :disabled="!photo">上传照片</el-button>
                          </div>
                          <div v-if="photo">
                            <h3>预览照片</h3>
                            <img :src="photo" alt="Captured Photo" width="320" height="240" />
                          </div>
                        </el-form-item>

                        <el-form-item label="文档图片:" prop="images">
                          <el-upload
                              action="/file/upload"
                              list-type="picture-card"
                              :file-list="imageList"
                              :on-preview="handlePictureCardPreview"
                              :on-remove="handleRemoveImage"
                              :on-success="handleImageSuccess"
                              :before-upload="beforeImageUpload"
                              :limit="5"
                              multiple>
                            <i class="el-icon-plus"></i>
                            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2MB</div>
                          </el-upload>
                          <el-dialog :visible.sync="dialogVisible">
                            <img width="100%" :src="dialogImageUrl" alt="">
                          </el-dialog>
                        </el-form-item>

                        <el-form-item label="文档文件:" prop="files">
                          <el-upload
                              class="upload-demo"
                              drag
                              action="/file/upload"
                              :file-list="fileList"
                              :on-success="handleFileSuccess"
                              :before-upload="beforeFileUpload"
                              :on-remove="handleRemoveFile"
                              :on-progress="handleProgress"
                              multiple>
                            <i class="el-icon-upload" style="margin-top: 20px"></i>
                            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                            <div slot="tip" class="el-upload__tip">支持多种文件格式，单个文件不超过10MB</div>
                          </el-upload>
                        </el-form-item>

                        <el-form-item label="用户账号:" prop="account">
                          <el-input v-model="form.account"></el-input>
                        </el-form-item>

                        <el-form-item label="用户姓名:" prop="username">
                          <el-input v-model="form.username"></el-input>
                        </el-form-item>
                      </el-form>
                    </div>

                    <div style="display: flex;align-items: center;justify-content: center;">
                      <el-button type="primary" @click="submitForm" :loading="submitting">保存</el-button>
                      <el-button type="default" @click="resetForm">返回</el-button>
                    </div>
                  </el-card>
                </el-main>
              </el-container>
            </el-container>
          </div>
        </template>

        <script>
          import axios from 'axios';

          export default {
            data() {
              return {
                form: {
                  file_name: '',
                  file_type: '',
                  account: '',
                  username: '',
                  images: [],
                  files: []
                },
                rules: {
                  name: [
                    { required: true, message: '请输入文档名称', trigger: 'blur' },
                    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
                  ],
                  type: [
                    { required: true, message: '请选择文档类型', trigger: 'change' }
                  ],
                  account: [
                    { required: true, message: '请输入用户账号', trigger: 'blur' }
                  ],
                  username: [
                    { required: true, message: '请输入用户姓名', trigger: 'blur' }
                  ]
                },
                imageList: [],
                fileList: [],
                dialogVisible: false,
                dialogImageUrl: '',
                photo: null,
                isCameraActive: false,
                submitting: false,
                uploadProgress: 0
              };
            },
            mounted() {
              axios.get('http://localhost:9000/file/').then(res =>{
                console.log(res)
              })
            },
            methods: {
              // 摄像头相关方法
              startCamera() {
                const video = this.$refs.video;
                navigator.mediaDevices.getUserMedia({ video: true })
                    .then(stream => {
                      video.srcObject = stream;
                      this.isCameraActive = true;
                    })
                    .catch(err => {
                      console.error("摄像头启动失败: ", err);
                      this.$message.error('摄像头启动失败，请检查权限设置');
                    });
              },

              capturePhoto() {
                const canvas = this.$refs.canvas;
                const video = this.$refs.video;
                const context = canvas.getContext('2d');
                context.drawImage(video, 0, 0, canvas.width, canvas.height);
                this.photo = canvas.toDataURL('image/png');
              },

              async uploadPhoto() {
                if (!this.photo) return;

                try {
                  const file = this.dataURLtoFile(this.photo, 'capture.png');
                  const formData = new FormData();
                  formData.append('file', file);

                  const response = await axios.post('/file/upload', formData, {
                    headers: {
                      'Content-Type': 'multipart/form-data'
                    }
                  });

                  this.form.images.push(response.data.data);
                  this.$message.success('照片上传成功');
                } catch (error) {
                  console.error('照片上传失败:', error);
                  this.$message.error('照片上传失败');
                }
              },

              // 文件上传相关方法
              beforeImageUpload(file) {
                const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPG) {
                  this.$message.error('上传图片只能是 JPG/PNG 格式!');
                }
                if (!isLt2M) {
                  this.$message.error('上传图片大小不能超过 2MB!');
                }
                return isJPG && isLt2M;
              },

              beforeFileUpload(file) {
                const isAcceptType = [
                  'application/pdf',
                  'application/msword',
                  'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                  'application/vnd.ms-excel',
                  'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                  'application/vnd.ms-powerpoint',
                  'application/vnd.openxmlformats-officedocument.presentationml.presentation',
                  'text/plain'
                ].includes(file.type);

                const isLt10M = file.size / 1024 / 1024 < 10;

                if (!isAcceptType) {
                  this.$message.error('不支持上传此类型文件!');
                }
                if (!isLt10M) {
                  this.$message.error('上传文件大小不能超过 10MB!');
                }
                return isAcceptType && isLt10M;
              },

              handleImageSuccess(response, file, fileList) {
                this.imageList = fileList;
                this.form.images = fileList.map(item => item.response ? item.response.data : item.url);
              },

              handleFileSuccess(response, file, fileList) {
                this.fileList = fileList;
                this.form.files = fileList.map(item => item.response ? item.response.data : item.url);
              },

              handleRemoveImage(file, fileList) {
                this.imageList = fileList;
                this.form.images = fileList.map(item => item.response ? item.response.data : item.url);
              },

              handleRemoveFile(file, fileList) {
                this.fileList = fileList;
                this.form.files = fileList.map(item => item.response ? item.response.data : item.url);
              },

              handleProgress(event, file, fileList) {
                this.uploadProgress = Math.round(event.percent);
              },

              handlePictureCardPreview(file) {
                this.dialogImageUrl = file.url;
                this.dialogVisible = true;
              },

              // 表单提交
              submitForm() {
                this.$refs.uploadForm.validate(async (valid) => {
                  if (!valid) {
                    this.$message.error('请填写完整表单信息');
                    return;
                  }

                  this.submitting = true;
                  try {
                    // 提交表单数据到后端
                    const response = await axios.post('/api/file/save', {
                      ...this.form,
                      userId: this.$store.state.user.userId // 从vuex获取当前用户ID
                    });

                    this.$message.success('文档保存成功');
                    this.resetForm();
                  } catch (error) {
                    console.error('文档保存失败:', error);
                    this.$message.error('文档保存失败');
                  } finally {
                    this.submitting = false;
                  }
                });
              },

              // 辅助方法
              dataURLtoFile(dataURL, filename) {
                const arr = dataURL.split(',');
                const mime = arr[0].match(/:(.*?);/)[1];
                const bstr = atob(arr[1]);
                let n = bstr.length;
                const u8arr = new Uint8Array(n);
                while (n--) {
                  u8arr[n] = bstr.charCodeAt(n);
                }
                return new File([u8arr], filename, { type: mime });
              },

              resetForm() {
                this.$refs.uploadForm.resetFields();
                this.imageList = [];
                this.fileList = [];
                this.photo = null;

                // 关闭摄像头
                if (this.isCameraActive) {
                  const video = this.$refs.video;
                  const stream = video.srcObject;
                  if (stream) {
                    const tracks = stream.getTracks();
                    tracks.forEach(track => track.stop());
                  }
                  this.isCameraActive = false;
                }
              }
            },
            beforeDestroy() {
              // 组件销毁前关闭摄像头
              if (this.isCameraActive) {
                const video = this.$refs.video;
                const stream = video.srcObject;
                if (stream) {
                  const tracks = stream.getTracks();
                  tracks.forEach(track => track.stop());
                }
              }
            }
          }
        </script>

        <style>
          /* 原有样式保持不变 */
          .el-menu--inline .el-menu-item{
            background-color: #000c17 !important;
          }
          .el-menu-item:hover,.el-submenu__title:hover{
            color: #fff !important;
          }
          .el-submenu:hover i{
            color: #fff !important;
          }
          .el-menu-item:hover i{
            color: #fff !important;
          }
          .el-header{
            height: 60px
          }

          .el-breadcrumb{
            margin-top: 20px;
          }
          .i{
            color: rgba(255,255,255,0.62);
          }
          .input{
            display: flex;align-items: center;justify-content: center;
          }
          .el-upload-dragger{
            height: 150px;
          }

          /* 新增样式 */
          .camera-upload {
            margin-bottom: 20px;
          }
          .camera-upload video {
            background-color: #000;
            margin-bottom: 10px;
          }
          .camera-upload button {
            margin-right: 10px;
          }
        </style>